package com.book.voice;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    
    private TextView attenuationText;
    private TextView systemVolumeText;
    private SeekBar attenuationSeekBar;
    private Switch attenuationSwitch;
    
    private AudioEffectManager audioEffectManager;
    private AudioManager audioManager;
    private BroadcastReceiver volumeReceiver;
    
    // 1dB = 100毫贝尔，范围从-15dB到0dB，步长1dB
    private static final int MIN_ATTENUATION = -1500; // -15dB
    private static final int MAX_ATTENUATION = 0;     // 0dB
    private static final int STEP_SIZE = 100;         // 1dB步长

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        Log.e(TAG, "=== MainActivity onCreate 开始 ===");
        Toast.makeText(this, "应用启动 - 开始初始化", Toast.LENGTH_SHORT).show();
        
        initializeViews();
        initializeAudioEffectManager();
        initializeAudioManager();
        setupVolumeReceiver();
        updateSystemVolumeDisplay();
        
        Toast.makeText(this, "初始化完成", Toast.LENGTH_SHORT).show();
        Log.e(TAG, "=== MainActivity onCreate 完成 ===");
    }

    private void initializeViews() {
        Log.e(TAG, "=== initializeViews 开始 ===");
        attenuationText = findViewById(R.id.attenuationText);
        systemVolumeText = findViewById(R.id.systemVolumeText);
        attenuationSeekBar = findViewById(R.id.attenuationSeekBar);
        attenuationSwitch = findViewById(R.id.attenuationSwitch);

        Log.e(TAG, "systemVolumeText = " + (systemVolumeText != null ? "找到" : "未找到"));
        
        // 测试TextView是否正常工作
        if (systemVolumeText != null) {
            systemVolumeText.setText("测试文本 - 如果能看到这个说明TextView正常");
            Log.e(TAG, "已设置测试文本到systemVolumeText");
            Toast.makeText(this, "TextView测试文本已设置", Toast.LENGTH_SHORT).show();
        } else {
            Log.e(TAG, "systemVolumeText为null，无法设置测试文本");
            Toast.makeText(this, "ERROR: TextView未找到", Toast.LENGTH_LONG).show();
        }

        // 设置SeekBar范围，步长为1dB (100毫贝尔)
        int maxProgress = (MAX_ATTENUATION - MIN_ATTENUATION) / STEP_SIZE;
        attenuationSeekBar.setMax(maxProgress);
        attenuationSeekBar.setProgress(0); // 默认-15dB (第0步)
        
        attenuationSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && audioEffectManager != null) {
                    // 将进度转换为调小值，步长为1dB
                    int attenuation = MIN_ATTENUATION + (progress * STEP_SIZE);
                    audioEffectManager.setAttenuation(attenuation);
                    updateAttenuationDisplay(attenuation);
                    
                    // 如果调小已开启，根据系统音量状态决定是否应用
                    if (attenuationSwitch.isChecked()) {
                        applyAttenuationIfNeeded();
                    }
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });

        attenuationSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                // 开启调小功能
                Toast.makeText(this, 
                    String.format("已开启调小: %.0f dB", audioEffectManager.getAttenuationInDb()), 
                    Toast.LENGTH_SHORT).show();
                // 根据当前系统音量状态决定是否立即应用
                applyAttenuationIfNeeded();
            } else {
                // 关闭调小功能
                if (audioEffectManager != null) {
                    audioEffectManager.releaseAllEffects();
                }
                Toast.makeText(this, "已关闭调小", Toast.LENGTH_SHORT).show();
            }
        });
        
        // 初始化显示默认值
        updateAttenuationDisplay(-1500);
        Log.e(TAG, "=== initializeViews 完成 ===");
    }

    private void initializeAudioEffectManager() {
        Log.e(TAG, "=== initializeAudioEffectManager ===");
        audioEffectManager = new AudioEffectManager(this);
    }

    private void initializeAudioManager() {
        Log.e(TAG, "=== initializeAudioManager ===");
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        Log.e(TAG, "audioManager = " + (audioManager != null ? "成功" : "失败"));
    }

    /**
     * 设置音量变化监听器
     */
    private void setupVolumeReceiver() {
        Log.e(TAG, "=== setupVolumeReceiver ===");
        volumeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.e(TAG, "=== 收到音量变化广播 ===");
                if ("android.media.VOLUME_CHANGED_ACTION".equals(intent.getAction())) {
                    Log.e(TAG, "系统音量发生变化");
                    updateSystemVolumeDisplay();
                    // 如果开关开启，检查是否需要应用音频调小
                    if (attenuationSwitch.isChecked()) {
                        applyAttenuationIfNeeded();
                    }
                }
            }
        };
        
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.media.VOLUME_CHANGED_ACTION");
        registerReceiver(volumeReceiver, filter);
        Log.e(TAG, "音量变化监听器已注册");
    }

    /**
     * 检查系统音量是否调到最小
     */
    private boolean isSystemVolumeAtMinimum() {
        if (audioManager != null) {
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            Log.e(TAG, "当前音量 = " + currentVolume);
            return currentVolume == 1; // 音量为 1 时表示最小
        }
        Log.e(TAG, "audioManager为null");
        return false;
    }

    /**
     * 更新系统音量显示
     */
    private void updateSystemVolumeDisplay() {
        Log.e(TAG, "=== updateSystemVolumeDisplay 开始 ===");
        
        if (audioManager != null) {
            int currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            
            Log.e(TAG, "当前音量 = " + currentVolume + ", 最大音量 = " + maxVolume);
            
            String displayText = String.format("当前系统音量: %d (范围: 0~%d)", currentVolume, maxVolume);
            Log.e(TAG, "显示文本 = " + displayText);
            
            if (systemVolumeText != null) {
                systemVolumeText.setText(displayText);
                Log.e(TAG, "文本已设置到TextView");
                Toast.makeText(this, "音量显示已更新: " + displayText, Toast.LENGTH_SHORT).show();
            } else {
                Log.e(TAG, "systemVolumeText为null");
                Toast.makeText(this, "ERROR: TextView为null", Toast.LENGTH_LONG).show();
            }
        } else {
            Log.e(TAG, "audioManager为null");
            Toast.makeText(this, "ERROR: AudioManager为null", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 根据系统音量状态决定是否应用音频调小
     */
    private void applyAttenuationIfNeeded() {
        Log.e(TAG, "=== applyAttenuationIfNeeded ===");
        if (audioEffectManager != null && attenuationSwitch.isChecked()) {
            if (isSystemVolumeAtMinimum()) {
                // 系统音量最小，应用音频调小
                Log.e(TAG, "系统音量最小，应用音频调小");
                audioEffectManager.applyAttenuation(0);
            } else {
                // 系统音量不是最小，释放音频效果（静默，用户无感知）
                Log.e(TAG, "系统音量不是最小，释放音频效果");
                audioEffectManager.releaseAllEffects();
            }
        } else {
            Log.e(TAG, "条件不满足，audioEffectManager=" + (audioEffectManager != null) + ", switchChecked=" + attenuationSwitch.isChecked());
        }
    }

    private void updateAttenuationDisplay(int attenuation) {
        double dbValue = attenuation / 100.0;
        attenuationText.setText(String.format("调小值: %.0f dB", dbValue));
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG, "=== onResume ===");
        // 更新系统音量显示
        updateSystemVolumeDisplay();
        // 每次回到应用时检查系统音量状态，静默应用或释放效果
        if (attenuationSwitch.isChecked()) {
            applyAttenuationIfNeeded();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "=== onDestroy ===");
        if (audioEffectManager != null) {
            audioEffectManager.releaseAllEffects();
        }
        // 注销音量变化监听器
        if (volumeReceiver != null) {
            unregisterReceiver(volumeReceiver);
            Log.e(TAG, "音量变化监听器已注销");
        }
    }
}